package cn.tianyigps.m7.netty;

import cn.tianyigps.m7.beans.Equipment;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Optional;

/**
 *
 * @Description:心跳检测机制,指定时间内未收到设备心跳断开连接
 * @date 2018/4/12 18:27
 */
public class ChatHeartbeatHandler extends ChannelInboundHandlerAdapter {
    //private final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("HB", CharsetUtil.UTF_8));
    Logger log = LogManager.getLogger(ChatHeartbeatHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            //ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            log(ctx);
            ctx.close();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    private void log(ChannelHandlerContext ctx) {
        TYChannelPipeline pipeline = (TYChannelPipeline) ctx.pipeline();
        if (Optional.ofNullable(pipeline).isPresent()) {
            Equipment equipment = pipeline.getEquipment();
            if (Optional.ofNullable(equipment).isPresent())
                log.info("设备下线 : " + equipment.getEquipmentId());
            else
                log.info("设备下线 :  .............");
        }
    }
}
